package band.wukong.practice.javase.core.thread.sync;

/**
 * Desc: 含有两个版本的Stack，一个线程不安全，一个线程安全。
 * Author: sunjs
 * Date: 2009-11-6 15:27:23
 */
public class NewStack {
    int point = -1;
    private String name;
    private String[] buffer = new String[200];

    public NewStack(String name) {
        this.name = name;
    }

    public String pop() {
        String goods = buffer[point];
        buffer[point] = null;
        Thread.yield();
        point--;
        return goods;
    }

    public void push(String goods) {
        point++;
        Thread.yield();
        buffer[point] = goods;
    }

    public String getName() {
        return name;
    }

    public int getPoint() {
        return point;
    }

    /**
     * 采用了同步机制的SynStack内部类
     */
    public static class SynStack extends NewStack {
        private NewStack newStack;

        public SynStack(NewStack stack) {
            super(stack.getName());
            this.newStack = stack;
        }

        public synchronized int getPoint() {
            return newStack.getPoint();
        }

        public synchronized String pop() {
            return newStack.pop();
        }

        public synchronized void push(String goods) {
            newStack.push(goods);
        }
    }

    /**
     * 返回一个NewStack对象的同步版本
     *
     * @param stack
     * @return
     */
    public static NewStack synchronizedStack(NewStack stack) {
        return new SynStack(stack);
    }
}
